package ccm.tools;

import ccm.component.image.AutoResizeableImageJPanel;
import ccm.component.image.ImageJPanel;
import ccm.component.image.ManualResizeableImageJPanel;
import ccm.component.override.TestJFrame;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;

public class GenerateImage extends TestJFrame implements ActionListener, ChangeListener
{
    private static final String[]    title=new String[]{"tools","GenerateImage"};
    protected final      ImageJPanel imageSourceJPanel;
    protected final      ImageJPanel imageResultJPanel;
    protected final      JButton     openJButton;
    protected final      JSpinner    widthJSpinner;
    protected final      JCheckBox   rotateJCheckBox;
    protected final      JCheckBox   fixedJCheckBox;
    protected final      JTextArea   jTextArea;
    protected final      JTextField  jTextField;
    protected final      JTextField  fixedXJCheckBox;
    protected final      JTextField  fixedYJCheckBox;
    protected final      JTextField  fixedWJCheckBox;
    protected final      JTextField  fixedHJCheckBox;
    protected final      JTextField  fixedLJCheckBox;

    public GenerateImage()
    {
        super(title);
        setSize(1200,900);
        setLayout(new BorderLayout());


        JSplitPane jSplitPane=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
        add(jSplitPane,BorderLayout.CENTER);
        jSplitPane.setOneTouchExpandable(true);
        jSplitPane.setDividerLocation(600);


        jSplitPane.add(imageSourceJPanel=new AutoResizeableImageJPanel());
        jSplitPane.add(imageResultJPanel=new ManualResizeableImageJPanel());

        JPanel jPanel=new JPanel();
        add(jPanel,BorderLayout.NORTH);
        jPanel.setLayout(new FlowLayout(FlowLayout.CENTER));

        openJButton=new JButton("打开");
        jPanel.add(openJButton);
        openJButton.addActionListener(this);

        jPanel.add(new JLabel("存储尺寸"));
        widthJSpinner=new JSpinner(new SpinnerNumberModel(90,0,10000,1));
        jPanel.add(widthJSpinner);
        widthJSpinner.addChangeListener(this);

        rotateJCheckBox=new JCheckBox("旋转");
        jPanel.add(rotateJCheckBox);
        rotateJCheckBox.addActionListener(this);

        jTextField=new JTextField("static inline void bspLcdShutdown",30);
        jPanel.add(jTextField);
        jTextField.addActionListener(this);

        JScrollPane jScrollPane;
        add(jScrollPane=new JScrollPane(jTextArea=new JTextArea()),BorderLayout.SOUTH);
        jTextArea.setEditable(false);
        jTextArea.setLineWrap(true);
        jScrollPane.setPreferredSize(new Dimension(100,400));


        fixedJCheckBox=new JCheckBox("固定坐标");
        jPanel.add(fixedJCheckBox);
        fixedJCheckBox.addActionListener(this);

        jPanel.add(new JLabel("x"));
        fixedXJCheckBox=new JTextField("0",5);
        jPanel.add(fixedXJCheckBox);
        fixedXJCheckBox.addActionListener(this);

        jPanel.add(new JLabel("y"));
        fixedYJCheckBox=new JTextField("0",5);
        jPanel.add(fixedYJCheckBox);
        fixedYJCheckBox.addActionListener(this);

        jPanel.add(new JLabel("w"));
        fixedWJCheckBox=new JTextField("0",5);
        jPanel.add(fixedWJCheckBox);
        fixedWJCheckBox.addActionListener(this);

        jPanel.add(new JLabel("h"));
        fixedHJCheckBox=new JTextField("0",5);
        jPanel.add(fixedHJCheckBox);
        fixedHJCheckBox.addActionListener(this);

        jPanel.add(new JLabel("lay"));
        fixedLJCheckBox=new JTextField("BSP_LCD_LAYER",10);
        jPanel.add(fixedLJCheckBox);
        fixedLJCheckBox.addActionListener(this);

        fixedXJCheckBox.setEnabled(fixedJCheckBox.isSelected());
        fixedYJCheckBox.setEnabled(fixedJCheckBox.isSelected());
        fixedLJCheckBox.setEnabled(fixedJCheckBox.isSelected());
        fixedWJCheckBox.setEnabled(fixedJCheckBox.isSelected());
        fixedHJCheckBox.setEnabled(fixedJCheckBox.isSelected());

        setVisible(true);
    }

    public static void main(String[] args)
    {
        new GenerateImage();
    }

    public String[] getTitleArray()
    {
        return title;
    }

    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource().equals(openJButton))
        {
            JFileChooser jFileChooser=new JFileChooser("");
            jFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            jFileChooser.showDialog(new JLabel(),"选择");
            try
            {
                imageSourceJPanel.setImage(ImageIO.read(jFileChooser.getSelectedFile()));
            }catch(IOException ex)
            {
                ex.printStackTrace();
            }
        }
        fixedXJCheckBox.setEnabled(fixedJCheckBox.isSelected());
        fixedYJCheckBox.setEnabled(fixedJCheckBox.isSelected());
        fixedLJCheckBox.setEnabled(fixedJCheckBox.isSelected());
        fixedWJCheckBox.setEnabled(fixedJCheckBox.isSelected());
        fixedHJCheckBox.setEnabled(fixedJCheckBox.isSelected());
        update();
    }

    private void update()
    {
        BufferedImage image=imageSourceJPanel.getImage();
        if(image==null)
            return;
        if(rotateJCheckBox.isSelected())
            image=getRotateImage(image);
        int w=(int)widthJSpinner.getValue();
        int h=image.getHeight()*w/image.getWidth();
        image=getScaledImage(image,w,h);
        imageResultJPanel.setImage(image);


        StringBuilder tmp=new StringBuilder();
        tmp.append("//@formatter:off\n").append(jTextField.getText());
        if(fixedJCheckBox.isSelected())
            tmp.append("(void){Point plu={").append(fixedXJCheckBox.getText()).append(",").append(fixedYJCheckBox.getText()).append("};uint16 disW=").append(fixedWJCheckBox.getText()).append(",disH=").append(fixedHJCheckBox.getText()).append(";ScnsLcdLayer layN=").append(fixedYJCheckBox.getText()).append(";");
        else
            tmp.append("(ScnsLcdLayer layN,Point plu,uint16 disW,uint16 disH){");
        tmp.append("if(disW==0&&disH==0){disW=").append(w).append(";disH=").append(h).append(";}else if(disH==0)disH=disW*").append(h).append("/").append(w).append(";else if(disW==0)disW=disH*").append(w).append("/").append(h).append(";plu.x=scnsMin(plu.x,scnsLcdGetBorder().x-disW);plu.y=scnsMin(plu.y,scnsLcdGetBorder().y-disH);");

        tmp.append("static const ScnsLcdColor data[]={");
        for(int i=0;i<h;++i)
            for(int j=0;j<w;++j)
            {
                int r=(image.getRGB(j,i)>>16)&0XFF;
                int g=(image.getRGB(j,i)>>8)&0XFF;
                int b=(image.getRGB(j,i))&0XFF;
                tmp.append(String.format("scnsLcdColorARGBToScreen(0XFF,0X%02X,0X%02X,0X%02X),",r,g,b));
            }
        tmp.append("};");

        tmp.append("scnsLcdDisplayArrayImage(layN,plu,data,SCNS_LCD_COLOR_FORMAT,NULL,").append(w).append(",").append(h).append(",disW,disH,0);}").append("\n//@formatter:off\n");
        // System.out.println(tmp.toString());
        jTextArea.setText(tmp.toString());
    }

    private BufferedImage getRotateImage(BufferedImage srcImg)
    {
        BufferedImage resizedImg=new BufferedImage(srcImg.getHeight(),srcImg.getWidth(),BufferedImage.TRANSLUCENT);
        for(int i=0;i<srcImg.getWidth();++i)
            for(int j=0;j<srcImg.getHeight();++j)
                resizedImg.setRGB(srcImg.getHeight()-1-j,i,srcImg.getRGB(i,j));
        return resizedImg;
    }

    private BufferedImage getScaledImage(BufferedImage srcImg,int w,int h)
    {
        BufferedImage resizedImg=new BufferedImage(w,h,BufferedImage.TRANSLUCENT);
        Graphics2D g2=resizedImg.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2.drawImage(srcImg.getScaledInstance(w,h,Image.SCALE_SMOOTH),0,0,w,h,null);
        g2.dispose();
        return resizedImg;
    }

    public void stateChanged(ChangeEvent e)
    {
        update();
    }
}
